package com.mobile.pilihsaya;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBClass extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "db_pilihsaya";

	
	public DBClass(Context context) {
		super(context, DATABASE_NAME, null, 1);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
		db.execSQL("CREATE TABLE if not exists tb_relawan "
				+ "(id_relawan INTEGER PRIMARY KEY AUTOINCREMENT, "
				+ "nama TEXT, " + "email TEXT, " + "alamat TEXT, " + "password TEXT, "
				+ "logdate DATE);");
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		db.execSQL("DROP TABLE IF EXISTS tb_relawan");
		onCreate(db);
	}
	
	public void InsertRelawan(Login login) {
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();

		values.put("id_relawan", login.getId_relawan());
		values.put("nama", login.getNama());
		values.put("password", login.getPassword());
		values.put("logdate", login.getLogdate().toString());
		db.insert("tb_relawan", null, values);
		db.close();

	}
	
	public boolean isLogin() {
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor c = db.rawQuery(
				"SELECT id_relawan, nama, email, alamat, password, logdate "
						+ "FROM tb_relawan LIMIT 1", new String[] {});

		if (c != null)
			c.moveToFirst();
		int count = c.getCount();
		c.close();
		db.close();
		if (count > 0) {
			return true;
		} else {
			return false;
		}

	}
	
	public void deleteRelawan() {
		SQLiteDatabase db = this.getWritableDatabase();
		String str = "DELETE from tb_relawan";
		db.execSQL(str);
		db.close();

	}
	
	public Login getLogin() {
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor c = db.rawQuery(
				"SELECT id_relawan, nama,email,alamat, password, logdate "
						+ "FROM tb_relawan LIMIT 1", new String[] {});

		if (c != null)
			c.moveToFirst();
		Login login = new Login(c.getInt(0), c.getString(1), c.getString(2),
				c.getString(3), c.getString(4), c.getString(4));

		c.close();
		db.close();

		return login;

	}

	
}
